<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="pd.showSearch">
        <el-form :model="pd.queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="计划名称" prop="scheduleName">
            <el-input v-model="pd.queryParams.scheduleName" placeholder="请输入计划名称" clearable style="width: 240px"
                      @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="产品名称" prop="productName">
            <el-input v-model="pd.queryParams.productName" placeholder="请输入产品名称" clearable style="width: 240px"
                      @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="开始生产" prop="startTime">
            <el-date-picker clearable
                            v-model="pd.queryParams.startTime"
                            type="date"
                            value-format="YYYY-MM-DD"
                            placeholder="请选择开始生产"
            />
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker clearable
                            v-model="pd.queryParams.endTime"
                            type="date"
                            value-format="YYYY-MM-DD"
                            placeholder="请选择结束时间" />
          </el-form-item>
          <el-form-item label="生产线" prop="workshopId">
            <el-select v-model="pd.queryParams.workshopId" placeholder="请选择生产线" clearable>
              <el-option v-for="item in pd.workShopLine" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="pd.queryParams.status" placeholder="请选择状态" clearable>
              <el-option v-for="dict in wms_schedule_line" :key="dict.value" :label="dict.name" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header #default="scope">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['wms:scheduleLine:add']">新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="pd.single" @click="handleUpdate(scope.row)"
                       v-hasPermi="['wms:scheduleLine:edit']">修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="pd.multiple" @click="handleDelete()"
                       v-hasPermi="['wms:scheduleLine:remove']">删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
                       v-hasPermi="['wms:scheduleLine:export']">导出
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="pd.showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="pd.loading" :data="pd.scheduleLineList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="计划名称" align="center" prop="scheduleName" />
        <el-table-column label="生产线名称" align="center" prop="workshopName" />
        <el-table-column label="产品名称" align="center" prop="productName" />
        <el-table-column label="物料清单名称" align="center" prop="bomName" />
        <el-table-column label="批次号" align="center" prop="batchCode" />
        <el-table-column label="开始生产" align="center" prop="startTime">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="endTime">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="wms_schedule_line" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="需求数量" align="center" prop="quantity" />
        <el-table-column label="已完成数量" align="center" prop="totalQuantityFinished" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column fixed="left" label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button v-show="scope.row.status === '0'" link type="primary" icon="Check" @click="Scheduling(scope.row)"
                       v-hasPermi="['']">排程
            </el-button>
            <el-button v-show="scope.row.status == '0'" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                       v-hasPermi="['wms:scheduleLine:edit']">修改
            </el-button>
            <el-button v-show="scope.row.status != '2'" link type="primary" icon="Delete"
                       @click="handleDelete(scope.row)" v-hasPermi="['wms:scheduleLine:remove']">删除
            </el-button>
            <text v-show="scope.row.status == '2'" type="success" icon="finished">完成</text>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="pd.total>0" :total="pd.total" v-model:page="pd.queryParams.pageNum"
                  v-model:limit="pd.queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改生产计划排程对话框 -->
    <el-dialog :title="pd.dialog.title" v-model="pd.dialog.visible" width="900" append-to-body>
      <el-form ref="scheduleLineFormRef" :model="pd.form" :rules="pd.rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="选择生产计划" prop="lineName">
              <scheduleSearch :data-text="pd.form.lineName" :is-show="false" :searchType="1" @ok="lineAdd"
                              title="请选择生产计划" />
            </el-form-item>
            <el-form-item label="计划id" prop="id">
              <el-input v-model="pd.form.id" placeholder="请输入计划id" disabled />
            </el-form-item>
            <el-form-item label="生产线id" prop="workshopId">
              <el-select v-model="pd.form.workshopId" placeholder="请选择生产线" clearable>
                <el-option v-for="item in pd.workShopLine" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="未排程数量" prop="quantityUnFinished">
              <el-input v-model="pd.form.quantityUnFinished" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="pd.form.productName" placeholder="请输入产品id" disabled />
            </el-form-item>
            <el-form-item label="物料清单" prop="bomId">
              <BomSearch :params="{productId:pd.form.productId}" :data-text="pd.form.bomName" :searchType="1"
                         @ok="lineAddBom" title="请选择物料" />
            </el-form-item>
            <el-form-item label="计划数量" prop="quantity">
              <el-input @input="checkNum(pd.form.quantity!)" v-model="pd.form.quantity" placeholder="请输入计划数量"
                        oninput="value=value.replace(/[^\d]/g, '')" />
            </el-form-item>
            <el-form-item label="已完成数量" prop="quantityCompletion">
              <el-input disabled v-model="pd.form.totalQuantityFinished" placeholder="请输入已完成数量" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="批次号" prop="batchCode">
              <el-popover
                placement="top-start"
                :width="200"
                trigger="hover"
                content="如果要分批次生成工单，请使用英文符号' ; '分割批次号，如 '111;2222'"
              >
                <template #reference>
                  <el-input v-model="pd.form.batchCode" placeholder="请输入批次号" />
                </template>
              </el-popover>
            </el-form-item>
            <el-form-item label="开始生产" prop="startTime">
              <el-date-picker clearable
                              v-model="pd.form.startTime"
                              type="datetime"
                              value-format="YYYY-MM-DD HH:mm:ss"
                              placeholder="请选择开始生产">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker clearable
                              v-model="computerEndTime"
                              type="datetime"
                              value-format="YYYY-MM-DD HH:mm:ss"
                              placeholder="请选择结束时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="已排程数量" prop="quantityCompletion">
              <el-input disabled v-model="pd.form.quantityInTask" />
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="pd.form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="pd.buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ScheduleLine" lang="ts">
import {
  addScheduleLine,
  delScheduleLine,
  listScheduleLine,
  ScheduleLineVO,
  updateScheduleLine
} from '@/views/wms/schedule/apiLine';
import scheduleSearch from "@/views/wms/schedule/search.vue";
import {ScheduleVO} from "@/views/wms/schedule/api";
import {listWorkshop} from "@/views/wms/workshopLine/api";
import BomSearch from "@/views/wms/bom/search.vue"
import {BomVO} from "@/views/wms/bom/api";
import {addTask, TaskVO} from "@/views/wms/task/api";

const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const {wms_schedule_line} = toRefs<any>(proxy?.useDict('wms_schedule_line'));
const queryFormRef = ref<ElFormInstance>();
const scheduleLineFormRef = ref<ElFormInstance>();

const pd = reactive({
  scheduleLineList: <ScheduleLineVO[]>([]),
  buttonLoading: false,
  loading: true,
  showSearch: true,
  selectVO: <ScheduleLineVO[]>([]),
  single: true,
  multiple: true,
  total: 0,
  line: [] as any,
  workShopLine: [] as any,
  form: <ScheduleLineVO>{},
  queryParams: <ScheduleLineVO>{
    pageNum: 1,
    pageSize: 10,
    id: undefined,
    workshopId: undefined,
    productId: undefined,
    startTime: undefined,
    endTime: undefined,
    status: undefined,
    params: {}
  },
  rules: <ElFormRules>{
    id: [
      {required: true, message: "计划id不能为空", trigger: "blur"}
    ],
    workshopId: [
      {required: true, message: "生产线id不能为空", trigger: "blur"}
    ],
    productId: [
      {required: true, message: "产品id不能为空", trigger: "blur"}
    ],
    status: [
      {required: true, message: "状态不能为空", trigger: "change"}
    ],
    batchCode: [
      {required: true, message: "批次号不能为空", trigger: "change"}
    ],
    bomId: [
      {required: true, message: "bom不能为空", trigger: "change"}
    ],
    quantity: [
      {required: true, message: "排程数量不能为空", trigger: "change"}
    ],
  },
  dialog: <DialogOption>{
    visible: false,
    title: ''
  }
});

// const { queryParams, form, rules } = toRefs(data);

/** 查询生产计划排程列表 */
async function getList() {
  pd.loading = true;
  const res = await listScheduleLine(pd.queryParams);
  pd.scheduleLineList = res.rows;
  pd.total = res.total;
  pd.loading = false;
}

/** 取消按钮 */
function cancel() {
  reset();
  pd.dialog.visible = false;
}

/** 表单重置 */
function reset() {
  pd.form = <ScheduleLineVO>{};
  pd.form.bomName = '';
  scheduleLineFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
function handleQuery() {
  pd.queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: ScheduleLineVO[]) {
  pd.selectVO = selection;
  pd.single = selection.length != 1;
  pd.multiple = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  pd.dialog.visible = true;
  pd.dialog.title = "添加生产计划排程";
  pd.form.status = "0";
  pd.form.batchCode = "0";
}

/** 修改按钮操作 */
async function handleUpdate(row: ScheduleLineVO) {
  reset();
  const data = row || pd.selectVO[0]
  const data2 = JSON.parse(JSON.stringify(data))
  Object.assign(pd.form, data2);
  if (pd.form.totalQuantity != undefined && pd.form.totalQuantityFinished != undefined) {
    pd.form.quantityUnFinished = pd.form.totalQuantity - pd.form.totalQuantityFinished
  }
  pd.form.lineName = row?.scheduleName;
  pd.dialog.title = "修改生产计划排程";
  pd.dialog.visible = true;
}

/** 提交按钮 */
function submitForm() {
  if (pd.form.quantity != undefined && pd.form.quantity <= 0) {
    proxy?.$modal.msgWarning("需求数量必须大于0！");
    return;
  }
  scheduleLineFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      pd.buttonLoading = true;
      if (pd.form.lineId) {
        await updateScheduleLine(pd.form).finally(() => pd.buttonLoading = false);
      } else {
        await addScheduleLine(pd.form).finally(() => pd.buttonLoading = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      pd.dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
async function handleDelete(row?: ScheduleLineVO) {
  const _lineIds = row?.lineId || pd.selectVO.map(v => v.lineId);
  await proxy?.$modal.confirm('是否确认删除生产计划排程编号为"' + _lineIds + '"的数据项？').finally(() => pd.loading = false);
  await delScheduleLine(_lineIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
function handleExport() {
  proxy?.download('wms/scheduleLine/export', {
    ...pd.queryParams
  }, `scheduleLine_${new Date().getTime()}.xlsx`)
}

/** 选择主生产计划 */
function lineAdd(vo: ScheduleVO) {
  const data = JSON.parse(JSON.stringify(vo))
  pd.form.id = data[0].id;
  pd.form.productId = data[0].productId;
  pd.form.productName = data[0].productName;
  pd.form.quantityUnFinished = data[0].quantity - data[0].quantityFinished - data[0].quantityInTask;
  pd.form.totalQuantityFinished = data[0].quantityFinished;
  pd.form.lineName = data[0].name;
  pd.form.quantityInTask = data[0].quantityInTask;
  pd.form.bomId = data[0].bomId;
  pd.form.bomName = data[0].bomName;
  pd.form.costTime = data[0].costTime;
  pd.form.quantity = 0;
  pd.line = [];
}

/** 选择物料清单 */
function lineAddBom(vo: BomVO) {
  const data = JSON.parse(JSON.stringify(vo))
  pd.form.bomId = data[0].id;
  pd.form.bomName = data[0].name;
  pd.form.costTime = data[0].costTime;
}

/** 计算结束时间 */
const computerEndTime = computed(() => {
  if (!pd.form.startTime && !pd.form.costTime && !pd.form.quantity) {
    return '';
  }
  const date = new Date(pd.form.startTime!);
  const millisecondsToAdd = pd.form.quantity! * pd.form.costTime! * 60 * 60 * 1000;
  date.setTime(date.getTime() + millisecondsToAdd);
  const dateParts = date.toLocaleString().split(" ");
  const [year, month, day] = dateParts[0].split("/") as [string, string, string];
  if (year && month && day) {
    const formattedDate = `${year}-${month.padStart(2, "0")}-${day.padStart(2, "0")} ${dateParts[1]}`;
    pd.form.endTime = formattedDate
    return formattedDate;
  } else return '';
});

/** 计算子生产线数量 */
function checkNum(num: number) {
  if (pd.form.quantityUnFinished) {
    if (pd.form.quantityUnFinished < 0) {
      pd.form.quantity = 0;
    } else if (num > pd.form.quantityUnFinished) {
      pd.form.quantity = pd.form.quantityUnFinished;
    }
  } else {
    pd.form.quantity = 0;
  }
}

/** 生产流水线 */
async function workShopLine() {
  const res = await listWorkshop();
  pd.workShopLine = res.rows;
}

/** 选择生产线 */
watch(() => pd.form.workshopId, async () => {
  if (pd.form.workshopId) {
    let query: ScheduleLineVO = {};
    query.workshopId = pd.form.workshopId;
    await listScheduleLine(query).then((res: any) => {
      //根据当前生产线最后的结束时间确定开始时间
      const date = new Date();
      for (const data of res.rows) {
        const endTime = new Date(data.endTime);
        if (endTime.getTime() > date.getTime()) {
          date.setTime(endTime.getTime())
        }
      }
      const dateParts = date.toLocaleString().split(" ");
      const [year, month, day] = dateParts[0].split("/") as [string, string, string];
      if (year && month && day) {
        pd.form.startTime = `${year}-${month.padStart(2, "0")}-${day.padStart(2, "0")} ${dateParts[1]}`
      }
    });
  }
})

//排程
async function Scheduling(row: ScheduleLineVO) {
  let vo = row;
  proxy?.$modal.confirm("排程后不可修改，确定排程？").then(async () => {
    if (vo.batchCode?.includes('；')) {
      proxy?.$modal.msgWarning("请使用英文分号作为分隔符！")
      return
    }
    const batchCode = vo.batchCode?.split(';');
    if (vo.quantity && batchCode) {
      for (let i = 0; i < batchCode.length; i++) {
        if (batchCode[i] === '' || batchCode[i] === null) {
          batchCode[i] = '0';
        }
      }
      if (vo.quantity % batchCode.length > 0) {
        proxy?.$modal.msgWarning(vo.quantity + "个需求数量无法平均分配给" + batchCode.length + "个工单，请修改后重试！")
        return;
      }
    }
    vo.status = "1";
    pd.loading = true;
    await updateScheduleLine(vo).then(() => {
      proxy?.$modal.msgSuccess("新增成功");
    }).finally(() => {
      pd.loading = false;
      getList();
    })
  })
}

onMounted(() => {
  getList();
  workShopLine()
});
</script>
